package com.bw.permission.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.bw.permission.config.AjaxResult;
import com.bw.permission.utils.DownLoadUtil;
import com.bw.permission.utils.HttpClientUtils;
import com.bw.permission.utils.JwtUtils;
import com.bw.permission.utils.WebUtils;
import com.zhanggm.hetong.hetong.entity.Hetong;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 合同控制器
 * @author zhanggm
 */
@Slf4j
@RestController
@RequestMapping("/hetong")
public class HetongController {

    @Autowired
    private JwtUtils jwtUtils;


    @Value("${file.path}")
    private String filePath;

    @Value("${file.domain}")
    private String fileDoamin;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询接口
     * @param hetong
     * @param pageNum
     * @param pageSize
     * @return PageInfo
     */
    @GetMapping("getPageInfo")
    public AjaxResult getPageInfo(Hetong hetong, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Map<String, Object> params = BeanUtil.beanToMap(hetong);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        //调用合同服务，设置超时时间2秒
        String resp = HttpUtil.get("http://localhost:8180/hetong/getPageInfo",params , 2000);
        return AjaxResult.ok(JSON.parseObject(resp));
    }

    /**
     * 保存合同
     * @param hetong
     * @return
     */
    @PostMapping("save")
    public AjaxResult save(@RequestBody Hetong hetong) {
        //获取请求Url和参数
        String requestURI = WebUtils.getRequest().getRequestURI();
        String params = JSON.toJSONString(hetong);
        //签名
        String token = SecureUtil.md5(requestURI + params);
        log.info("token:{}",token);
        //redis表单防重复提交 setnx
        if (!redisTemplate.opsForValue().setIfAbsent(token, null,10, TimeUnit.SECONDS)) {
            log.info("表单重复提交了");
            return AjaxResult.err(400,"不能重复提交");
        }
        /*Map<String, Object> params = BeanUtil.beanToMap(hetong);*/
        //获取当前登录用户
        Integer curUserId = jwtUtils.getCurUserId();
        hetong.setUserId(curUserId);
        //请求接口的唯一标识，保证接口幂等性
        Map<String, Object> hetongMap = BeanUtil.beanToMap(hetong);
        hetongMap.put("uuid", UUID.randomUUID().toString());
        //调用合同服务保存合同，设置超时时间2秒
        String uuid = UUID.randomUUID().toString();
        String resp = null;
        try{
            resp = HttpClientUtils.post("http://localhost:8180/hetong/save", JSON.toJSONString(hetongMap), 2000);
        }catch (Exception e){
            e.printStackTrace();
            log.info("服务调用异常，重试");
            resp = HttpClientUtils.post("http://localhost:8180/hetong/save", JSON.toJSONString(hetongMap), 2000);
        }
        return AjaxResult.ok(JSON.parseObject(resp));
    }

    /**
     * 查询合同
     * @param hetong
     * @return
     */
    @GetMapping("getById")
    public AjaxResult getById(Hetong hetong) {
        Map<String, Object> params = BeanUtil.beanToMap(hetong);
        //调用合同服务保存合同，设置超时时间2秒
        String resp = HttpUtil.get("http://localhost:8180/hetong/getById", params, 2000);
        return AjaxResult.ok(JSON.parseObject(resp));
    }



    /**
     * 审核
     * @param hetong
     * @return
     */
    @GetMapping("check")
    public AjaxResult check(Hetong hetong) {
        if (!jwtUtils.isRole("xiaoshouzongjian")) {
            return AjaxResult.err(400,"销售总监才能审核合同");
        }
        Map<String, Object> params = BeanUtil.beanToMap(hetong);
        log.info("params:{}",params);
        String resp = HttpUtil.get("http://localhost:8180/hetong/check",params , 2000);
        return AjaxResult.ok();
    }

    /**
     * 创建合同pdf
     * @param hetong
     * @throws Exception
     */
    @PostMapping("createPdf")
    public AjaxResult createPdf(@RequestBody Hetong hetong) throws Exception{
        Map<String, Object> params = BeanUtil.beanToMap(hetong);
        log.info("params:{}",params);
        String resp = HttpUtil.post("http://localhost:8180/hetong/createPdf",JSON.toJSONString(params) , 2000);
        return AjaxResult.ok();
    }

    /**
     * 预览合同
     * @param hetong
     * @return
     */
    @RequestMapping("previewPdf")
    public AjaxResult previewPdf(Hetong hetong){
        String pdf=fileDoamin+hetong.getId()+".pdf";
        return AjaxResult.ok(pdf);
    }

    @RequestMapping("downloadCheck")
    public AjaxResult downloadCheck(Hetong hetong) throws IOException {
        /*if (jwtUtils.isRole("")) {
            return AjaxResult.ok();
        }*/
        return AjaxResult.err();
    }
    /**
     * 下载合同
     * @param hetong
     * @return
     * @throws IOException
     */
    @RequestMapping("download")
    public AjaxResult download(Hetong hetong) throws IOException {

        HttpServletResponse response = WebUtils.getResponse();
        String fileName = filePath+hetong.getId()+".pdf";
        DownLoadUtil.download(response,fileName,hetong.getMingcheng()+hetong.getId()+".pdf",0);
        return AjaxResult.ok();
    }

}
